package web.jsoft.com;

import java.util.EnumSet;
import java.util.Set;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import service.jsoft.com.GaeUserAuthentication;
import service.jsoft.com.UserRegistry;

import com.google.appengine.api.users.UserServiceFactory;
import domain.jsoft.com.AppRole;
import domain.jsoft.com.GaeUser;

@ManagedBean
@RequestScoped
public class RegisterBean {
	private String firstname;
	private String lastname;
	private UserRegistry registry; 
	
	public void setRegistry(UserRegistry registry){
		this.registry = registry;
	}

	public UserRegistry getRegistry(){
		return this.registry;
	}
	
	public void setFirstname(String firstname){
		this.firstname = firstname;
	}

	public String getFirstname(){
		return this.firstname;
	}
	
	public void setLastname(String lastname){
		this.lastname = lastname;
	}

	public String getLastname(){
		return this.lastname;
	}

	public String registerUser(){
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
	    GaeUser currentUser = (GaeUser)authentication.getPrincipal();
	    Set<AppRole> roles = EnumSet.of(AppRole.USER);

	    if (UserServiceFactory.getUserService().isUserAdmin()) {
	        roles.add(AppRole.ADMIN);
	    }

	    GaeUser user = new GaeUser(currentUser.getUserId(), currentUser.getNickname(), currentUser.getEmail(),
	    		firstname, lastname, roles, true);

	    registry.registerUser(user);

	    // Update the context with the full authentication
	    SecurityContextHolder.getContext().setAuthentication(new GaeUserAuthentication(user, authentication.getDetails()));
		return "success";
	}
}
